package com.eurasia.assignment.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.eurasia.assignment.controller.dto.CreateCourseRequest;
import com.eurasia.assignment.domain.Course;
import com.eurasia.assignment.infrastructure.entity.CourseEntity;
import com.eurasia.assignment.infrastructure.repository.CourseRepository;

/**
 * 课程服务类
 * 提供课程相关的业务逻辑
 */
@Service
public class CourseService {

    private final CourseRepository courseRepository;

    @Autowired
    public CourseService(CourseRepository courseRepository) {
        this.courseRepository = courseRepository;
    }

    /**
     * 创建新课程
     * @param request 课程创建请求
     * @return 创建的课程
     */
    @Transactional
    public Course createCourse(CreateCourseRequest request) {
        // 检查课程名称是否已存在
        if (courseRepository.existsByCourseName(request.getCourseName())) {
            throw new IllegalArgumentException("课程名称已存在: " + request.getCourseName());
        }
        
        // 创建课程对象
        Course course = Course.create(
            request.getCourseName(),
            request.getCourseType(),
            request.getCredit(),
            request.getSelectedCount(),
            request.getDescription()
        );
        
        // 保存到数据库
        var savedCourse = courseRepository.save(CourseEntity.fromDomain(course));

        return savedCourse.toDomain();
    }
} 